<?php
/**
 * ListMallProduct.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/11/17- 10:43 上午
 */

namespace common\models\es\dataProvider\tbMallProducts;

use Yii;

class ListMallProduct extends Query
{

    public function getData()
    {
        $params = [
            'index' => $this->getIndexName(),
            'body' => $this->getBody()
        ];
//        exit();
//        echo "<pre>";
//        print_r($params);
//        exit();
//        print_r($this->query);
        $esResult = Yii::$app->elasticsearch->search($params);
        $count = $esResult['hits']['total']['value'] ?? 0;
        $list = $esResult['hits']['hits'] ?? [];
        return [$list, $count];
    }

    /**
     * es标题重复铺货
     * @return array
     */
    public function getDataRepeatGoodsName()
    {
        $params = [
            'index' => $this->getIndexName(),
            'body' => $this->getBody()
        ];

//        print_r($this->query);
//        print_r(json_encode($params['body'])); exit;
        $esResult = Yii::$app->elasticsearch->search($params);
        return $esResult['aggregations']['goodsIdField']['buckets'] ?? [];
    }


    /**
     * 拼装请求体
     * @return array
     */
    protected function getBody()
    {
        if (isset($this->query['is_repeat_title'])) {
            $return = [
                'track_total_hits' => true,
                '_source' => $this->fields,
                'query' => $this->getQueryBody(),
                'sort' => $this->sort,
                'aggs' => [
                    'goodsIdField' => [
                        'terms' => [
                            'field' => 'goods_name',
                            'size' => 500,
                            'min_doc_count' => 2
                        ]
                    ]
                ]
            ];
        } else if (isset($this->query['is_repeat_image'])) {
            $return = [
                'track_total_hits' => true,
                '_source' => $this->fields,
                'query' => $this->getQueryBody(),
                'sort' => $this->sort,
                'aggs' => [
                    'goodsIdField' => [
                        'terms' => [
                            'field' => 'image_url_base',
                            'size' => 500,
                            'min_doc_count' => 2,
                        ]
                    ]
                ]
            ];
        } else {
            $return = [
                'track_total_hits' => true,
                '_source' => $this->fields,
                'size' => $this->size,
                'from' => $this->from,
                'query' => $this->getQueryBody(),
                'sort' => $this->sort
            ];
        }
        if (isset($this->query['goods_name']) && $this->query['goods_name']) {
            $return['highlight'] = ['fields' => ['goods_name' => (object)[]]];
        }
        return $return;
    }

    protected function getQueryBody()
    {
        return [
            'bool' => [
                'filter' => $this->getFilter()
            ],
        ];
    }

    /**
     * 拼装过滤条件
     * @return array
     */
    protected function getFilter(): array
    {

        $filter = [];
        //用户ID
        if (isset($this->query['uid']) && !empty($this->query['uid'])) {
            $filter[] =
                ['term' => ['uid' => $this->query['uid']]];
        }

        //店铺id
        if (isset($this->query['mall_id']) && !empty($this->query['mall_id'])) {
            $filter[] =
                ['terms' => ['mall_id' => $this->query['mall_id']]];
        }

        //所属类目cid
        if (isset($this->query['cat_id'])) {
            $filter[] =
                ['terms' => ['cat_id' => $this->query['cat_id']]];
        }

        //商品类型
        if (isset($this->query['goods_type'])) {
            $filter[] =
                ['term' => ['goods_type' => $this->query['goods_type']]];
        }

        //商家编码
        if (isset($this->query['outer_goods_id'])) {
            $filter[] =
                ['terms' => ['outer_goods_id' => $this->query['outer_goods_id']]];
        }

        //商品上下架状态
        if (isset($this->query['approve_status'])) {
            $filter[] =
                ['term' => ['status' => $this->query['approve_status']]];
        }

        //商品上下架状态
        if (isset($this->query['approve_status_arr'])) {
            $filter[] =
                ['terms' => ['status' => $this->query['approve_status_arr']]];
        }

        //有无商家编码
        if (isset($this->query['isset_outer_id'])) {
            if ($this->query['isset_outer_id'] == 1) {
                $filter[] = [
                    'bool' => [
                        'must_not' => [
                            'term' => ['outer_goods_id' => ''],
                        ]
                    ]
                ];
            }
            if ($this->query['isset_outer_id'] == 2) {
                $filter[] = [
                    'bool' => [
                        'must' => [
                            'term' => ['outer_goods_id' => ''],
                        ]
                    ]
                ];
            }
        }

        //根据商品名称搜索关键词
        if (isset($this->query['goods_name']) && !empty($this->query['goods_name'])) {

            $filter[] = [
                'bool' => [
                    'must' => [
                        'wildcard' => ['goods_name' => '*' . $this->query['goods_name'] . '*'],
                    ]
                ]
            ];
//            $filter[] = [
//                ['match_phrase' => ['goods_name' => $this->query['goods_name']]]
//            ];
        }
        //根据违禁词搜索
        if (isset($this->query['words']) && !empty($this->query['words'])) {
            $words = [];
            foreach ($this->query['words'] as $k => $v) {
                if ($v == '?' || $v == '\\') {
                    $v = "\\" . $v;
                }
                $goods_info =
                    array(
                        'wildcard' => array(
                            'goods_name' => '*' . $v . '*'
                        )
                    );
                $words[] = $goods_info;
            }

            $filter[] = [
                'bool' => [
                    'should' => $words
                ]
            ];
        }

        //重复铺货
        if (isset($this->query['goods_name_repeat']) && !empty($this->query['goods_name_repeat'])) {
            $words = [];
            foreach ($this->query['goods_name_repeat'] as $k => $v) {
                $goods_info =
                    array(
                        'wildcard' => array(
                            'goods_name' => $v
                        )
                    );
                $words[] = $goods_info;
            }

            $filter[] = [
                'bool' => [
                    'should' => $words
                ]
            ];
        }

        if (isset($this->query['goods_image_repeat']) && !empty($this->query['goods_image_repeat'])) {
            $words = [];
            foreach ($this->query['goods_image_repeat'] as $k => $v) {
                $goods_info =
                    array(
                        'wildcard' => array(
                            'image_url_base' => $v
                        )
                    );
                $words[] = $goods_info;
            }

            $filter[] = [
                'bool' => [
                    'should' => $words
                ]
            ];
        }


//        $filter[] = [
//            'bool' => [
//                'should' => [
//                    ['wildcard' => [ 'goods_name' =>  '*太平鸟*' ]]
//                    ,
//                    ['wildcard' => [ 'goods_name' =>  '*爆款爆款衣服*' ]]
//                ]
//            ]
//        ];
//        echo "<pre>";
//        print_r($filter);
//        exit();
        //运费模板
        if (isset($this->query['cost_template_id'])) {
            $filter[] =
                ['term' => ['cost_template_id' => $this->query['cost_template_id']]];
        }
        //是否预售
        if (isset($this->query['is_pre_sale']) && $this->query['is_pre_sale'] != null) {
            $filter[] =
                ['term' => ['is_pre_sale' => $this->query['is_pre_sale']]];
        }
        //退换货
        if (isset($this->query['is_refundable']) && $this->query['is_refundable'] != null) {
            $filter[] =
                ['term' => ['is_refundable' => $this->query['is_refundable']]];
        }

        //是否二手
        if (isset($this->query['second_hand']) && $this->query['second_hand'] != null) {
            $filter[] =
                ['term' => ['second_hand' => $this->query['second_hand']]];
        }

        //假一罚十
        if (isset($this->query['is_folt']) && $this->query['is_folt'] != null) {
            $filter[] =
                ['term' => ['is_folt' => $this->query['is_folt']]];
        }
        //是否搬家
        if (isset($this->query['is_copy']) && $this->query['is_copy'] != null) {
            $filter[] =
                ['term' => ['is_copy' => $this->query['is_copy']]];
        }


        //商品ID
        if (isset($this->query['goods_ids']) && !empty($this->query['goods_ids'])) {
            $filter[] = [
                "terms" => ['goods_id' => $this->query['goods_ids']]
            ];
        }

        /**
         * 价格区间检索
         */
        if (isset($this->query['min_price']) || isset($this->query['max_price'])) {
            $priceTep = [];
            if (isset($this->query['min_price']) && !empty($this->query['min_price'])) {
                $priceTep['from'] = $this->query['min_price'];
            }

            if (isset($this->query['max_price']) && !empty($this->query['max_price'])) {
                //截止时间加上一天的时间戳
                $priceTep['to'] = $this->query['max_price'];
            }
            if (count($priceTep)) {
                $filter[] = [
                    "range" => [
                        'sale_price' => $priceTep
                    ]
                ];
                unset($priceTep);
            }
        }

        /**
         * 库存区间
         */
        if (isset($this->query['start_num']) || isset($this->query['end_num'])) {
            $timeTep = [];
            if (isset($this->query['start_num']) && !empty($this->query['start_num'])) {
                $timeTep['from'] = $this->query['start_num'];
            }

            if (isset($this->query['end_num']) && !empty($this->query['end_num'])) {
                //截止时间加上一天的时间戳
                $timeTep['to'] = $this->query['end_num'];
            }
            if (count($timeTep)) {
                $filter[] = [
                    "range" => [
                        'goods_quantity' => $timeTep
                    ]
                ];
                unset($timeTep);
            }
        }


        /**
         * 上架时间区间
         */
        if (isset($this->query['start_list_time']) || isset($this->query['end_list_time'])) {
            $timeTep = [];
            if (isset($this->query['start_list_time']) && !empty($this->query['start_list_time'])) {
                $timeTep['from'] = $this->query['start_list_time'];
            }

            if (isset($this->query['end_list_time']) && !empty($this->query['end_list_time'])) {
                //截止时间加上一天的时间戳
                $timeTep['to'] = $this->query['end_list_time'];
            }
            if (count($timeTep)) {
                $filter[] = [
                    "range" => [
                        'list_time' => $timeTep
                    ]
                ];
                unset($timeTep);
            }
        }
        return $filter;
    }


}
